package dtd.PHS.VND_ExchangeRate.utils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import dtd.PHS.VND_ExchangeRate.R;
import dtd.PHS.VND_ExchangeRate.data.ListRates;
import dtd.PHS.VND_ExchangeRate.data.RateItem;
import dtd.PHS.VND_ExchangeRate.data.SJCItem;
import dtd.PHS.VND_ExchangeRate.data.VNExDatabase;

public class Helpers {
	public static final boolean DEBUG_MODE = false;
	public static final String PREF_FIRST_TIME_RUNNING = "pref_first_time_running";
	public static final String PREF_DATE = "Pref_current_exchange_rate_date";
	public static final String PREF_CREATED_TIME = "pref_created_time";
	public static final String PREF_LAST_TAB_ID = "pref_last_main_tab_id";
	public static final String[] PREF_LAST_CHOOSEN_SPINNER = {"pref_last_spinner01","pref_last_spinner02"};
	public static final String PREF_LAST_CHOOSEN_PREVIEW_SMS = "pref_last_choosen_preview_sms";
	public static final String PREF_SELECTED_CURRENCIES = "pref_selected_currencies";
	private static final String PREF_LANGUAGE = "pref_language";
	public static final String VIETNAMESE = "vi";
	public static final String ENGLISH = "en";
	private static final String DEFAULT_LANGUAGE = VIETNAMESE;
	public static final String PREF_GOLD_ITEM = "pref_gold_price";


	public static void initGlobalData(Context context) {
		ApplicationContext.setContext( context );
		MyHandler.getInstance();
		if ( isFirstTimeRunning() ) {
			try {
				VNExDatabase.createDBFromStatic();
				VNExDatabase.setCreatedTimeDB(0);
				Helpers.setPreference(Helpers.PREF_FIRST_TIME_RUNNING,"false");
			} catch (Exception e) {
				Logger.logError("Init global data: Exception: " + e.getClass().toString() + " :: "  + e.getMessage());
			}
		}
	}
	public static boolean isFirstTimeRunning() {
		try {
			String isFirstTime = Helpers.getPreference(Helpers.PREF_FIRST_TIME_RUNNING);
			if ( isFirstTime == null)
				return true;
			return false;
		} catch (Exception e) {
			return false;
		}
	}

	public static void setPreference(String prefName, String data) {
		Context context = ApplicationContext.getContext();
//		SharedPreferences settings = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(prefName, data);
		editor.commit();
	}

	public static String getPreference(String prefName) {
		Context context = ApplicationContext.getContext();
//		SharedPreferences settings = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		String prefData = settings.getString(prefName, null); 
		return prefData;        
	}

	public static boolean isConnectedToInternet() {
		try {
			ConnectivityManager conMgr = (ConnectivityManager) ApplicationContext.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);  
			NetworkInfo info = conMgr.getActiveNetworkInfo();  
			if ( info != null && info.isConnected() ) {
				return true;
			} else	return false;
		} catch (Exception e) {
			return false;
		}
	}

	public static View inflateView(int viewResId, ViewGroup dad) {
		Context context = ApplicationContext.getContext();
		LayoutInflater i = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		return i.inflate(viewResId, dad);
	}

	public static View inflateView(Activity act,int viewResId, ViewGroup dad) {
		LayoutInflater i = act.getLayoutInflater();
		return i.inflate(viewResId, dad);
	}


	public static int getFlagIconName(String currencyName) {
		currencyName = currencyName.toLowerCase();
		String fileName = currencyName + "_flag";
		Context context = ApplicationContext.getContext();
		return context.getResources().getIdentifier(fileName, "drawable", context.getPackageName());
	}

	public static String formatRate(double rate) {
		int intRate = (int) rate; 
		return NumberFormat.getInstance().format(intRate);
	}
	public static ArrayList<String> split(String sentence,String seperator) {
		String[] words = sentence.split(seperator);
		ArrayList<String> ret = new ArrayList<String>();

		for(String word : words) {
			if ( word.trim().length() != 0) {
				ret.add(word);
			}
		}

		return ret;
	} 

	public static String createSMSContent(
			RateItem rate,
			String date) {
		Context context = ApplicationContext.getContext();
		String content = context.getString(R.string.SMS_Title) + " " + date + "\n\n";
		content += createSMSBodyForRate(rate);
		content += context.getString(R.string.SMSBottomLine);
		return content;
	}

	public static String createSMSContent(SJCItem goldPrice) {
		Context context = ApplicationContext.getContext();
		String content = context.getString(R.string.SMS_Title_Gold_Price) + ",\n" + goldPrice.getUpdateTimeString() + "\n\n";
		content += context.getString(R.string.Buying_SMS)+ ": " + formatRate(goldPrice.getBuying()) + "\n";
		content += context.getString(R.string.Selling_SMS)+": " + formatRate(goldPrice.getSelling()) + "\n";
		content += "\n";
		content += context.getString(R.string.SMSBottomLine);
		return content;
	}


	public static String createSMSContent(
			ListRates rates, 
			String date) {
		Context context = ApplicationContext.getContext();
		String content = context.getString(R.string.SMS_Title) + " " + date + "\n\n";
		for(RateItem rate: rates) {		 
			content += createSMSBodyForRate(rate);
		}
		content += context.getString(R.string.SMSBottomLine);
		return content;
	}

	public static void broadcastSMSIntent(String content) {
		Context context = ApplicationContext.getContext();
		Intent sendIntent = new Intent(Intent.ACTION_VIEW);
		sendIntent.putExtra("sms_body", content); 
		sendIntent.setType("vnd.android-dir/mms-sms");
		sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(sendIntent);
	}

	public static String createSMSBodyForRate(RateItem rate) {
		Context context = ApplicationContext.getContext();
		String content = "---"+rate.getCurrencyName()+"---\n";
		content += context.getString(R.string.Buying_SMS)+ ": " + formatRate(rate.getBuying()) + "\n";
		content += context.getString(R.string.Transfer_SMS)+": " + formatRate(rate.getTransfer())+ "\n";
		content += context.getString(R.string.Selling_SMS)+": " + formatRate(rate.getSelling()) + "\n";
		content += "\n";
		return content;
	}

	static public String getRidOfComma(String numberStr) {	
		return numberStr.replaceAll(",", "");
	}

	static public boolean isValidLong(String numberStr) {
		try {
			long d = Long.parseLong(numberStr);
			if ( d >= 0 ) return true;
			return false;
		} catch (NumberFormatException ne) {
			return false;
		}	
	}

	static public String formatCurrency(String amount) {
		amount = getRidOfComma(amount);
		int cnt = 0;
		String x = new String("");
		for(int i = amount.length()-1; i>=0 ; i--) {
			cnt++;
			x = amount.charAt(i)+x;
			if ( cnt == 3 && i != 0) {
				cnt = 0;			
				x = ','+x ;
			}
		}
		return x;

	}

	static public int newCursorPosition(int prePos,String preS,String aftS) {			
		int aftPos = prePos;			
		if (preS.length() < aftS.length()) {
			//Insert a char	
			aftPos = prePos + 1 + ((preS.length() + 1) % 4 == 0 ? 1:0);				
		} else if (preS.length() > aftS.length()){
			//Delete a char by Backspace			
			aftPos = prePos - 1;
			if ( prePos == 1) return 0;
			aftPos = aftPos - ((preS.length() - 1) % 4 == 0 ? 1:0);				
		}				
		//Only the case insert/delete at the end
		//	prove why is this case enough
		return aftPos;
	}

	public static void showToast(String text) {
		Context context = ApplicationContext.getContext();
		Toast.makeText(context, text, Toast.LENGTH_LONG).show();
	}
	public static void broadcastEmailIntent(Activity hostedActivity, String content) {
		Context context = ApplicationContext.getContext();
		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		emailIntent .setType("plain/text");
		emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{});
		String subject = context.getString(R.string.vietcombank_exchange_rate);  
		emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
		emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, content);
		hostedActivity.startActivity(Intent.createChooser(emailIntent, "Send mail..."));		
	}


	public static void saveLanguageOption(String languageToLoad) {
		setPreference(PREF_LANGUAGE,languageToLoad);
	}

	public static void changeLanguage(Activity act,String languageToLoad) {
		if (languageToLoad == null ) languageToLoad = DEFAULT_LANGUAGE;
		Resources res = act.getResources();
		// Change locale settings in the app.
		DisplayMetrics dm = res.getDisplayMetrics();
		android.content.res.Configuration conf = res.getConfiguration();
		conf.locale = new Locale(languageToLoad);
		res.updateConfiguration(conf, dm);
	}

	public static void forceActivityRestart(Activity act) {
		act.finish();
		act.startActivity(act.getIntent());
	}

//	public static void killProcess(Activity activity) {
////		activity.finish();
////		android.os.Process.killProcess(android.os.Process.myPid());
//	}
	
	public static void launchHomeScreen(Activity activity) {
		Intent startMain = new Intent(Intent.ACTION_MAIN);
		startMain.addCategory(Intent.CATEGORY_HOME);
		startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		activity.startActivity(startMain);		
	}
	
	public static String getLanguagePreference() {
		String lang = getPreference(PREF_LANGUAGE);
		if (lang == null) 
			lang = DEFAULT_LANGUAGE;
		return lang;
	}

	public static void hideSoftKeyboard(Activity act, View view) {
		InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
	}
	public static String formatGoldPrice(int buying) {
		return NumberFormat.getInstance().format(buying); 
	}

}
